package com.linko.soundrecorder;

import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by zhongrz on 15-3-27.
 */
public class CustomCheckBoxPreference extends Preference implements View.OnClickListener {
    private ImageView mCheckStateImage;

    public CustomCheckBoxPreference(Context context) {
        super(context);
        setLayoutResource(R.layout.custom_preference_item);
    }

    public CustomCheckBoxPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        setLayoutResource(R.layout.custom_preference_item);
    }

    public CustomCheckBoxPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setLayoutResource(R.layout.custom_preference_item);
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        View preference = view.findViewById(R.id.preference_item);
        TextView title = (TextView) preference.findViewById(R.id.title);
        title.setText(getTitle());
        TextView summary = (TextView) preference.findViewById(R.id.summery);
        summary.setText(getSummary());
        mCheckStateImage = (ImageView) preference.findViewById(R.id.on_of);
        final boolean isChecked = getSharedPreferences().getBoolean(getKey(), false);
        mCheckStateImage.setImageResource(isChecked ? R.drawable.ic_checked : R.drawable.ic_uncheck);
        preference.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        final boolean isChecked = getSharedPreferences().getBoolean(getKey(), false);
        getEditor().putBoolean(getKey(), !isChecked).commit();
        final boolean newState = getSharedPreferences().getBoolean(getKey(), false);
        mCheckStateImage.setImageResource(newState ? R.drawable.ic_checked : R.drawable.ic_uncheck);
    }
}
